// 路由鉴权
import router from "@/router";
//@ts-ignore
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import setting from "./setting";
import useUserStore from "./store/modules/user";
import pinia from "./store";

const userStore = useUserStore(pinia);
// 全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  document.title = `${setting.title} - ${to.meta.title}`;
  nprogress.start();
  const token = userStore.token;
  const username = userStore.username;
  if (token) {
    if (to.path == "/login") {
      next(false);
    } else {
      if (username) {
        next();
      } else {
        try {
          await userStore.userInfo();
          //注:刷新的时候是异步路由,有可能获取到用户信息、异步路由还没有加载完毕,出现空白的效果
          next({ ...to, replace: true });
        } catch (error) {
          //token过期
          //用户手动修改本地存储token
          //退出登录->用户相关的数据清空
          await userStore.userLogout();
          next({ path: "/login", query: { redirect: to.path } });
        }
      }
    }
  } else {
    //用户未登录判断
    if (to.path == "/login") {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});

// 全局后置守卫
router.afterEach((to: any, from: any) => {
  nprogress.done();
});
